<template>
	<view class="wy-page" :style="page.style" :class="[screenClass,page.dfclass,page.class,'wy-theme-'+ThemeName]">
		<view class="wy-flex-column wy-flex-1" :style="boxHeight+body.boxStyle">
			<view  :style="bodyHeight+body.style"  class="wy-page-body" :class="body.dfclass+' '+body.class">
				<slot v-if="screen.open && screen.slots.small.includes(page.screen)" name="small"></slot>
				<slot v-if="screen.open && screen.slots.wide.includes(page.screen)" name="wide"></slot>
				<slot v-if="screen.open && screen.slots.medium.includes(page.screen)" name="medium"></slot>
				<slot></slot>
			</view>
			<view v-if="foot.show" class="wy-align-center"  :style="foot.style" :class="foot.dfclass+' '+foot.class">
				<slot name="foot"></slot>
				<text class="wy-footer wy-size-ss">{{footContent}}</text>
			</view>
		</view>
	</view>
</template>

<script>
    import {wy,pubfn} from '../../libs/context.js' 
    var getHeight = pubfn?.getHeight  
	export default {
		name: "wy-page",
		options: {// 微信小程序中 options 选项
		    virtualHost: true,
			styleIsolation: 'apply-shared'
		},
        provide() {
        	return {
        		wyPage: this
        	};
        },
		inject: {
			wyPages: {
				default () {
					return null
				}
			}
		},
		data() {
			return {
				hook:{ //页面钩子
					enable:false,
					pagekey:'' 
				},
				page:{
					dfclass:'wy-flex-column wy-flex-1 wy-position-relative', //组件最外层默认样式
					class:'',//组件最外自定义
					style:'',
					name:'' ,//标识
					screen:'', //媒体查询宽度
					height:'', //媒体查询高度
                    theme:'',//主题
                    wechatFit:true //微信h5环境，自动去掉导航条
				},
				head:{ 
					title:'',//导航栏标题
                    backgroundColor:'',
                    frontColor:''
				},
				body:{
					dfclass:'wy-flex-1 wy-flex-column',
					class:'',
					style:'',
					boxStyle:'',
					height:'',
					boxHeight:'window'
				},
				foot:{
					dfclass:'wy-flex-column wy-align-center wy-ps-top-s wy-ps-bottom-s',
					class:'',
					style:'',
					contentClass:'',
					contentStyle:'',
					show:false,
					auto:true,
					content:''
				},
				screen:{
					open:true,
					slots:{
						small:['small'],
						medium:['medium','wide'],
						wide:[]
					}
				},
				bodyHeight:'',
				boxHeight:'',
				mediaDb:null,
				inWechat:false,
                isPageShow:true
			};
		},
		props: {
			pageData:{
				type:Object,
				default:()=>{
					return{
					}
				}
			},
			screenQuery:{
				type:Boolean,
				default:true
			},
			heightQuery:{
				type:Boolean,
				default:false
			},
			mediaQuery:{
				type:Object,
				default:()=>{
					return{
						screen:{
							open:false,
						},
						height:{
							open:false
						}
					}
				}
			},
			pageName:{
				type:String,
				default:''
			} 
		},
		watch:{
			pageData:{
				handler(){
					this.init()
				},
				deep:true
			},
            ThemeClass(val){
                var that=this
                this.addWaitEmit(()=>{
                    that.setModel(val)
                    let {backgroundColor,frontColor}=that.head 
                    if(backgroundColor && frontColor){
                    	that.setNavbackgroundColor({backgroundColor,frontColor})
                    }
                },'onPageShow',this.isPageShow)
                
            }
		},
		mounted() {
            let pages = getCurrentPages();
            if(pages.length>0){
                this._currentPage=pages[pages.length - 1]; 
            } 
            this._waitEmits={}
			this.notice('mounted')
			this.loadMediaQuery() 
		},
		unmounted() {
			if(this.mediaDb){
				this.mediaDb.disconnect()
			}
		},
		created() {
          //  pubfn =wy.pubfn;
            this.subs=[]
			this.init()
		},
		computed:{ 
            ThemeName(){
              return wy.getters('core/ThemeName')  
            },
            ThemeClass(){
              return wy.getters('core/ThemeClass')  
            },
			footContent(){
				let {auto,content}=this.foot
				if(!content&&auto){
					//自动生成
					var sitename=this.locale(wy.config.App.sitename,true)
					return '©'+new Date().getFullYear()+' '+sitename
					+' All rights reserved.'
				}
				else{
					return this.locale(content,true)
				}
			},
            screenClass(){ 
                return  'wy-screen-'+this.page.screen //+' wy-theme-'+(this.page.theme?this.page.theme:this.ThemeName)
            }
		}, 
		methods: {
            addWaitEmit(call,name='',excuteNow=false){
                if(excuteNow){
                    call()
                }
                else{
                   if(!this._waitEmits){
                       this._waitEmits={} 
                   }
                   if(this._waitEmits.hasOwnProperty(name)){
                       this._waitEmits[name].push(call)
                   }
                   else{
                       this._waitEmits=Object.assign(this._waitEmits,{[name]:[call]})
                   }  
                }
                
            },
			locale(key,isContent=false){
				return wy.locale(key,isContent)
			},
            //注册机制，表个单规范
            register(ref,name='',uuid='',callback=null){
                console.log('page-register--'+name+' '+uuid)
                this.subs.push({ref,name,uuid,callback})
            },
            //设置属性 表个单规范
            setModel(model){ 
                for(let key in model){
                    if(this[key] && pubfn.isObject(model[key])){
                        this[key]=pubfn.deepMerge(this[key],model[key])
                    }
                }
            },
            //事件通知 表个单规范
            notice(event,data=null){
                this.subs.forEach((e)=>{
                    let {name,uuid,callback}=e
                    if(callback){
                        callback({
                            event,
                            data,
                            name,uuid
                        })
                    }
                })
                if(event=='onPageShow'){
                    this.isPageShow=true
                   //  console.log(event,this._waitEmits)
                }
                else if(event=='onPageHide'){
                    this.isPageShow=false
                }
               
                if(this._waitEmits && this._waitEmits.hasOwnProperty(event)){
                   
                    var calls=this._waitEmits[event]
                    calls.forEach((call)=>{
                        call(data)
                    })
                    delete this._waitEmits[event]
                }
                this.$emit(event,data) 
            },
			loadMediaQuery(){
				if(this.mediaQuery){
					let that=this
					var medias=wy.config.Sys.mediaQuery
					medias=pubfn.deepMerge(medias,{...this.mediaQuery})
					if(this.screenQuery){
						medias=pubfn.deepMerge(medias,{screen:{open:true}})
					}
					if(this.heightQuery){
						medias=pubfn.deepMerge(medias,{height:{open:true}})
					}
					// #ifdef H5 || APP-VUE
					this.mediaDb=uni.createMediaQueryObserver(that)
					// #endif
					// #ifdef MP || APP-NVUE
					const {windowWidth,windowHeight} = uni.getSystemInfoSync();
					// #endif
					for(let key in medias){
						let {open,matches}=medias[key]
						if(open){
							for(let val in matches){
								 const option=matches[val]
								 // #ifdef H5 || APP-VUE
									this.mediaDb.observe(option,res=>{
										if(res){
											that.notice(key,val)
											that.page.screen=val
                                            setTimeout(that.autoSize,0) 
										}
									})
								// #endif

								// #ifdef MP || APP-NVUE
								if(key=='screen'){
									let {minWidth,maxWidth}=option 
									if((!minWidth||minWidth<=windowWidth)&&(!maxWidth||maxWidth>windowWidth)){
										that.notice(key,val)
										that.page.screen=val
									}
								}
								else if(key=='height'){
									let {minHeight,maxHeight}=option
									if((!minHeight||minHeight<=windowHeight)&&(!maxHeight||maxHeight>windowHeight)){
										
                                        that.notice(key,val)
										that.page.hegiht=val 
									}
								}
								// #endif
							}
						}
					}

				}
			},
			getInstance(){
				return this
			},
			init() { 
                let theme=wy.getters('core/ThemeName') //wy.vk.getVuex('core.theme')
				let themeClass=wy.getters('core/ThemeClass')//wy.vk.getVuex('core.themeClass')
				let pageObj=this.pageData
				if(themeClass){
                    this.setModel(themeClass)
					//pageObj=pubfn.deepMerge(themeClass,this.pageData)
				} 
				let {head,body,foot,page,hook}=pageObj
				if(page){
					this.page=pubfn.deepMerge(this.page,{theme},page)
				}
                let {wechatFit}=this.page
                //var navH=0
                //#ifdef H5
                //微信浏览器自动隐藏标题栏
                if(wechatFit){
                    var ua = navigator.userAgent.toLowerCase();
                    if(ua.match(/MicroMessenger/i)=="micromessenger") {
            　　　　　　//在微信浏览器
                        setTimeout(()=>{
                            let pageNav = document.getElementsByTagName("uni-page-head");
                            if (pageNav && pageNav[0]) {
                                pageNav[0].style.display = "none";
                            }
                        },0)
                        //navH=getHeight('nav')
                        this.inWechat=true
                        this.notice('inWechat','micromessenger')
                    }  
                } 
                // #endif 
				if(head){
					this.head=pubfn.deepMerge(this.head,head)
				}
                
                let {show,title,backgroundColor,frontColor}=this.head
                
                if(backgroundColor&&frontColor){
                	this.setNavbackgroundColor({backgroundColor,frontColor})
                }
                if(title && !this.wyPages){
                	this.setNavbar({title})
                }
				if(body){
					this.body=pubfn.deepMerge(this.body,body)
				}
				if(foot){
					this.foot=pubfn.deepMerge(this.foot,foot)
				}
				if(hook){
					this.setPageHook(hook)
				}
				var name=this.pageName?this.pageName:this.page.name
				if(this.wyPages && name){
					this.wyPages.register(this.getInstance,name)
				}
				var pageRef = wy.getPageRef(this) 
                if(pageRef && pageRef._register){
                    pageRef._register(this.getInstance,name)
                }
				setTimeout(this.autoSize,0) 
			},
            autoSize(){ 
                var navH=this.inWechat?getHeight('nav'):0 
                let {height,boxHeight}=this.body
                this.bodyHeight=height?('min-height:'+(getHeight(height)+navH)+'px;'):''
                this.boxHeight=boxHeight?('min-height:'+(getHeight(boxHeight)+navH)+'px;'):'' 
            },
			initPageHooks(hook=null){
				if(hook==null){
					hook=this.hook
				}
				let{enable,pagekey}=hook
				if(!pagekey){
					let pages = getCurrentPages();
					let currentPage = pages[pages.length - 1];
					pagekey = currentPage.route;
					this.hook.pagekey=pagekey
				}
				if(enable){
					this.setPageHook()
				}
			},
			setPageHook(){
				let {pagekey,data}=this.hook
				wy.hooks(pagekey,data,function(result){
					this.notice('pageHook',{name,data,result})
				},'page')
			},
			setNavbackgroundColor(option){
				uni.setNavigationBarColor(option)
			},
			setNavbar(option){
				let {title}=option
				if(title){
					uni.setNavigationBarTitle({
						title
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
